package br.com.amadeus.android.activities.course.forum;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.amadeus.android.activities.course.material.HomeResourceActivity;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.adapters.ForumMessageListAdapter;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Config;
import br.com.amadeus.android.entities.CourseUser;
import br.com.amadeus.android.entities.Forum;
import br.com.amadeus.android.entities.Message;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;
import br.com.amadeus.android.util.JSONReader;
import br.com.amadeus.android.util.RESTFileContent;
import br.com.amadeus.android.util.Util;

public class ForumActivity extends Activity implements OnClickListener {
	
	protected static final String CATEGORIA = "curso";
	private EditText etResponse;
	private Button bSend, bCancel, bAnswer;
	private ListView lvMessages;
	ArrayList<Message> messageList = null;
	private FacadeAmadeusDroid facade = null;
	private int forum_id;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.forum_messages);
		
		this.facade = FacadeAmadeusDroid.getInstance(this);
		
		initComponents();
						
		Bundle gotBasket = getIntent().getExtras();
		this.forum_id = gotBasket.getInt("forum_id");
		
		Forum forum = facade.getForum(forum_id);
		
		TextView tvForumName = (TextView) findViewById(R.id.tvForumName);
		tvForumName.setText(forum.getName());
		
		TextView tvDesc = (TextView) findViewById(R.id.tvDescription);
		tvDesc.setText("Descrição: " + forum.getDescription());
		
		TextView tvAber = (TextView) findViewById(R.id.tvAbertura);
		
		tvAber.setText("Abertura: " + Util.getDataHoraFormatoCompleto(forum.getCreationDate()));
				
		messageList = facade.getListMessagesByForum(forum.getId());
			
		this.lvMessages.setAdapter(new ForumMessageListAdapter(this, messageList));
		
		//Ocultar o Teclado após o uso de editText
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(this.etResponse.getWindowToken(), 0);
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		finish();
	}

	private void initComponents() {
		
		this.etResponse = (EditText) findViewById(R.id.etResponse);
		this.bSend = (Button) findViewById(R.id.bSend);
		this.bCancel = (Button) findViewById(R.id.bCancel);
		this.bAnswer = (Button) findViewById(R.id.bAnswer);
		this.lvMessages = (ListView) findViewById(R.id.lvMessages);
				
		this.bSend.setOnClickListener(this);
		this.bCancel.setOnClickListener(this);
		this.bAnswer.setOnClickListener(this);
		
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bAnswer:
			
			SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
			String pref = getPrefs.getString("listPref", "1");
			int opcao = Integer.parseInt(pref);
			
			switch (opcao) {
			case ConstantsAmadeusDroid.MODO_ONLINE:
				
				this.etResponse.setVisibility(View.VISIBLE);
				this.bSend.setVisibility(View.VISIBLE);
				this.bCancel.setVisibility(View.VISIBLE);
				
				break;

			case ConstantsAmadeusDroid.MODO_OFFLINE:
				
				Toast.makeText(ForumActivity.this, "Não é possível responder ao fórum no Modo de Acesso offline.", Toast.LENGTH_SHORT).show();
				
				break;
			}			
			
			break;
		case R.id.bSend:
						
			String body = this.etResponse.getText().toString();
			Date date = new Date();
			Config cfg = FacadeAmadeusDroid.getInstance(this).getConfig();
			String personName = cfg.getUser_name();
			String personLogin = cfg.getUser_login();
			Forum forum = FacadeAmadeusDroid.getInstance(this).getForum(this.forum_id);
			
			Message message = new Message(0, body, date, personName, forum, 0, personLogin);
			ArrayList<CourseUser> list = FacadeAmadeusDroid.getInstance(this).getListCourseUser();
			CourseUser obj = list.get(0);
			message.setPerson_id(obj.getUser().getId());
			
			//Envia para Amadeus Web
			RESTFileContent rfc = new RESTFileContent();
			try {
				String url = cfg.getAmadeus_url() + ConstantsAmadeusDroid.HOST_AMADEUS_WEB_POST_MESSAGE;
				InputStream is = rfc.sendForumMessageToAmadeusWeb(url, message);
				String msgJson = rfc.toString(is);
				Message msg = JSONReader.getMessageFromAmadeusWeb(msgJson);
				message.setAmadeus_id(msg.getAmadeus_id());
			} catch (ClientProtocolException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			} catch (IOException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			} catch (JSONException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
			}
			
			//Grava no SQLite
			FacadeAmadeusDroid.getInstance(this).insertForumMessage(message);
			
			//Refresh na Activity
			Bundle basket = new Bundle();
			basket.putInt("forum_id", forum.getId());
			Intent it = new Intent("FORUM");
			it.putExtras(basket);
			startActivity(it);
			
			break;
		case R.id.bCancel:
			this.etResponse.setVisibility(View.INVISIBLE);
			this.bSend.setVisibility(View.INVISIBLE);
			this.bCancel.setVisibility(View.INVISIBLE);
			break;
		
		}
		
	}
	
}
